import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { getHttp, putHttp } from '../../request/api';

interface Doctor {
    doctorId: number;
    doctorName: string;
    imagePic: string;
    jobTitle: string;
    inauguralHospital: string;
    praise: number;
    serverNum: number;
    servicePrice: number;
    praiseNum: number;
    badNum: number;
}

interface DoctorListState {
    doctors: Doctor[];
    loading: boolean;
    error: string | null;
    hasMore: boolean;
    page: number;
    deptId: number;
    condition: number;
    sortBy: number | undefined;
}

const initialState: DoctorListState = {
    doctors: [],
    loading: false,
    error: null,
    hasMore: true,
    page: 1,
    deptId: 1,
    condition: 1,
    sortBy: undefined,
};

export const fetchDoctors = createAsyncThunk(
    'doctors/fetchDoctors',
    async (params: { deptId: number; condition: number; sortBy?: number; page: number; count: number }) => {
        const response = await getHttp('/health/user/inquiry/v1/findDoctorList', params);
        return response.data;
    }
);

export const consultDoctor = createAsyncThunk(
    'doctors/consultDoctor',
    async (doctorId: number) => {
        const userInfoStr = localStorage.getItem('userInfo');
        if (!userInfoStr) {
            throw new Error('请先登录');
        }

        const userInfo = JSON.parse(userInfoStr);
        const { userId, sessionId } = userInfo;

        const response = await putHttp(
            '/health/user/inquiry/verify/v1/consultDoctor',
            { doctorId },
            {
                headers: {
                    'userId': userId.toString(),
                    'sessionId': sessionId
                }
            }
        );
        return response.data;
    }
);

const doctorSlice = createSlice({
    name: 'doctors',
    initialState,
    reducers: {
        resetDoctors: (state) => {
            state.doctors = [];
            state.page = 1;
            state.hasMore = true;
        },
        setDeptId: (state, action: PayloadAction<number>) => {
            state.deptId = action.payload;
            state.doctors = [];
            state.page = 1;
            state.hasMore = true;
        },
        setCondition: (state, action: PayloadAction<number>) => {
            state.condition = action.payload;
            state.doctors = [];
            state.page = 1;
            state.hasMore = true;
        },
        setSortBy: (state, action: PayloadAction<number | undefined>) => {
            state.sortBy = action.payload;
            state.doctors = [];
            state.page = 1;
            state.hasMore = true;
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchDoctors.pending, (state) => {
                state.loading = true;
                state.error = null;
            })
            .addCase(fetchDoctors.fulfilled, (state, action) => {
                state.loading = false;
                if (action.payload.status === 'success') {
                    const newDoctors = action.payload.result;
                    state.doctors = [...state.doctors, ...newDoctors];
                    state.hasMore = newDoctors.length === 10;
                    state.page += 1;
                } else {
                    state.error = action.payload.message || '获取医生列表失败';
                }
            })
            .addCase(fetchDoctors.rejected, (state, action) => {
                state.loading = false;
                state.error = action.error.message || '加载失败，请稍后重试';
            });
    },
});

export const { resetDoctors, setDeptId, setCondition, setSortBy } = doctorSlice.actions;
export default doctorSlice.reducer; 